package com.hitalkie.teacher.widget.pageview;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * TODO 固定头（sticky header ，pinnder header ）https://github.com/edubarr/header-decor
 * TODO 优化header footer 的使用
 */
public class PageRecyclerView extends RecyclerView {

    public static enum State{
        IDLE, LOADING, END
    }
    private OnLastItemVisibleListener mOnLastItemVisibleListener;

    public State loadingStatus = State.IDLE;

    private OnScrollListener onScrollListener;

    public PageRecyclerView(Context context) {
        super(context);
        init();
    }

    public PageRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PageRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        onScrollListener = new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                switch (loadingStatus){
                    case IDLE:
                        //TODO  only support LinearLayoutManager for now
                        if (getLayoutManager() instanceof LinearLayoutManager) {
//                            Log.e("Marr","last:"+((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition() +"total position:"+ (getAdapter().getItemCount()-1));
                            if (((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition() != getAdapter().getItemCount() - 1) {
                                return;
                            }
                            loadingStatus = State.LOADING;
                            if(mOnLastItemVisibleListener!=null){
                                mOnLastItemVisibleListener.onLastItemVisible();
                            }
                        }
                        break ;
                    case LOADING:
                        return ;
                    case END:
                        return ;
                }


            }
        };
        addOnScrollListener(onScrollListener);
    }

    public void setOnLastItemVisibleListener(OnLastItemVisibleListener listener) {
        mOnLastItemVisibleListener = listener;
    }

}
